package com.mightykiwi.controllers;

import java.util.ArrayList;
import java.util.List;

import com.mightykiwi.beans.Contact;
import com.mightykiwi.beans.UserMK;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.json.JsonArray;
import com.restfb.json.JsonObject;

public class ContactsController {

	private static ContactsController instance;

	private ContactsController() { }

	public static ContactsController getInstance() {
		if(instance == null)
			instance = new ContactsController();
		return instance;
	}

	public List<Contact> getContacts(UserMK user) {
		List<Contact> contacts = new ArrayList<Contact>();

		FacebookClient fbClient = new DefaultFacebookClient(user.getAccess_token());

		JsonObject friendsConnection = fbClient.fetchObject("me/friends", JsonObject.class);
		JsonArray jsonArray = friendsConnection.getJsonArray("data");
		int length = jsonArray.length();
		for(int i = 0; i < length; i++) {
			JsonObject obj = (JsonObject)jsonArray.get(i);
			Contact contact = new Contact();
			contact.setSocial_network(user.getSocial_network());
			contact.setNom((String)obj.get("name"));
			contact.setSn_id((String)obj.get("id"));
			contacts.add(contact);
		}
		return contacts;
	}
}
